package com.onenine.app.activity;

import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.onenine.app.R;
import com.onenine.app.event.NearbyConditionEvent;
import com.onenine.app.model.LabelItem;
import com.onenine.app.model.NearbyCondition;
import com.onenine.app.request.GetLabelsRequest;
import com.onenine.app.response.GetLabelsResponse;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.RoleResLoader;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BaseActivity;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.StatusBarUtils;
import com.onenine.base.view.seekbar.OnRangeChangedListener;
import com.onenine.base.view.seekbar.RangeSeekBar;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.ScreenUtils;
import com.onenine.common.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * 筛选条件
 */
public class NearbyConditionActivity extends BaseActivity implements OnRangeChangedListener
        , RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private static NearbyCondition sCondition = new NearbyCondition();
    private RangeSeekBar mAgeSeekBar, mDistSeekBar;
    private FlexboxLayout mFlexLayout;
    private RadioGroup mRgSex;
    private RadioButton mRbMale, mRbFemale, mRbAll;
    private Button mBtnConfirm, mBtnCancel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        StatusBarUtils.setTransparent(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_nearby_condition;
    }

    @Override
    protected void setStatusBarStyle() {
    }

    private void setWindowTheme() {
        Window window = getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.gravity = Gravity.TOP;
        wl.width = WindowManager.LayoutParams.MATCH_PARENT;
        wl.height = (int) (0.9 * ScreenUtils.getScreenHeight());
    }

    @Override
    protected void initViews() {
        super.initViews();
        setWindowTheme();
        mBtnCancel = findViewById(R.id.btn_clear);
        mAgeSeekBar = findViewById(R.id.sb_age);
        mDistSeekBar = findViewById(R.id.sb_dist);
        mRgSex = findViewById(R.id.rg_sex);
        mFlexLayout = findViewById(R.id.fb_layout);
        mBtnConfirm = findViewById(R.id.btn_confirm);
        int indicColor = RoleResLoader.getRoleColorResourceId(RoleResLoader.DynamicResName.THEME_COLOR);
        mAgeSeekBar.setProgressColor(indicColor);
        mDistSeekBar.getLeftSeekBar().setIndicatorBackgroundColor(indicColor);
        mAgeSeekBar.getLeftSeekBar().setIndicatorBackgroundColor(indicColor);
        mDistSeekBar.setProgressColor(indicColor);
        mBtnConfirm.setBackgroundResource(RoleResLoader
                .getRoleDrawableResourceId(RoleResLoader.DynamicResName.THEME_GRADIENT_CORNER_BG));
        mRbFemale = findViewById(R.id.rb_female);
        mRbFemale.setTextColor(RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_TEXT_BG));
        mRbFemale.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_BG));
        mRbMale = findViewById(R.id.rb_male);
        mRbMale.setTextColor(RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_TEXT_BG));
        mRbMale.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_BG));
        mRbAll = findViewById(R.id.rb_all);
        mRbAll.setTextColor(RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_TEXT_BG));
        mRbAll.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_BG));
    }

    @Override
    protected void initListeners() {
        super.initListeners();
        mAgeSeekBar.setOnRangeChangedListener(this);
        mDistSeekBar.setOnRangeChangedListener(this);
        mRgSex.setOnCheckedChangeListener(this);
        mBtnConfirm.setOnClickListener(this);
        mBtnCancel.setOnClickListener(this);
        findViewById(R.id.btn_quit).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        initConditionSelect();
        getLabelsByType();
    }

    /**
     * 初始化条件选择
     */
    private void initConditionSelect() {
        mAgeSeekBar.setRange(NearbyCondition.DEFAULT_AGE_BEGIN, NearbyCondition.DEFAULT_AGE_END);
        mAgeSeekBar.setValue(sCondition.getAgee());
        mDistSeekBar.setRange(0, NearbyCondition.DEFAULT_DISTANCE);
        mDistSeekBar.setValue(sCondition.getDistance() / 1000);
        mRgSex.check(sCondition.getSex() == DataType.SEX_MALE ? R.id.rb_male
                : sCondition.getSex() == DataType.SEX_FEMALE ? R.id.rb_female : R.id.rb_all);
        onRangeChanged(mAgeSeekBar, sCondition.getAgee(), sCondition.getAgee(), true);
        onRangeChanged(mDistSeekBar, sCondition.getDistance() / 1000, 0, true);
    }

    /**
     * 拉取标签列表
     */
    private void getLabelsByType() {
        GetLabelsRequest request = new GetLabelsRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setLabelType(DataType.MY_LABEL);
        OkRequest.getInstance().withUrl(UrlConfig.QUERY_LABEL)
                .withRequest(request).doRequest(NearbyConditionActivity.class.getSimpleName(), new OkCallback<GetLabelsResponse>() {
            @Override
            public void onResponse(GetLabelsResponse response, String srcData) {
                if (response.isSuccess()) {
                    handleLabels(response.getLabelItemList());
                }
            }
        });
    }

    /**
     * 显示并处理标签
     *
     * @param labelList
     */
    private void handleLabels(List<LabelItem> labelList) {
        final List<String> selectList = sCondition.getLabels();
        Resources resources = ApUtils.getApp().getResources();
        int labelWidth = resources.getDimensionPixelOffset(R.dimen.label_width_large);
        int labelHeight = resources.getDimensionPixelOffset(R.dimen.label_height_large);
        int labelMargin = SizeUtils.dp2px(10);
        for (final LabelItem label : labelList) {
            TextView tvLabel = (TextView) getLayoutInflater().inflate(R.layout.layout_label_item, null, false);
            tvLabel.setText(label.getLabelName());
            tvLabel.setBackgroundResource(RoleResLoader.getRoleDrawableResourceId(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_BG));
            tvLabel.setTextColor(RoleResLoader.getRoleColorStateList(RoleResLoader.DynamicResName.SELECTOR_LABEL_ITEM_TEXT_BG));
            FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(labelWidth, labelHeight);
            layoutParams.setMargins(labelMargin, labelMargin, labelMargin, labelMargin);
            mFlexLayout.addView(tvLabel, -1, layoutParams);
            setLabelSelect(tvLabel, selectList.contains(label.getLabelId()));
            tvLabel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getTag() == null) {
                        setLabelSelect(tvLabel, true);
                        sCondition.addLabel(label.getLabelId());
                    } else {
                        setLabelSelect(tvLabel, false);
                        sCondition.removeLabel(label.getLabelId());
                    }
                }
            });
        }
    }

    /**
     * 设置标签的可选状态
     *
     * @param tvLabel
     * @param isSelected
     */
    private void setLabelSelect(TextView tvLabel, boolean isSelected) {
        tvLabel.setTag(isSelected ? true : null);
        tvLabel.setSelected(isSelected);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, R.anim.slide_out_top);
    }

    @Override
    public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
        if (view.getId() == R.id.sb_age) {
            mAgeSeekBar.setIndicatorText(String.format("0-%d", (int) leftValue));
            sCondition.setAgee((int) leftValue);
        } else if (view.getId() == R.id.sb_dist) {
            sCondition.setDistance((int) leftValue * 1000);
            mDistSeekBar.setIndicatorText(String.format("%dkm", (int) leftValue));
        }
    }

    @Override
    public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

    }

    @Override
    public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_male:
                sCondition.setSex(DataType.SEX_MALE);
                break;
            case R.id.rb_female:
                sCondition.setSex(DataType.SEX_FEMALE);
                break;
            default:
                sCondition.setSex(0);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_confirm) {
            EventBus.getDefault()
                    .post(new NearbyConditionEvent(sCondition));
            finish();
        } else if (v.getId() == R.id.btn_clear) {
            sCondition.reset();
            initConditionSelect();
            resetLabelsSelect();
        } else if (v.getId() == R.id.btn_quit) {
            finish();
        }
    }

    /**
     * 清空标签选择
     */
    private void resetLabelsSelect() {
        for (int i = 0; i < mFlexLayout.getChildCount(); i++) {
            mFlexLayout.getChildAt(i).setSelected(false);
        }
    }

    @Override
    protected void onDestroy() {
        OkRequest.getInstance()
                .cancelTag(NearbyConditionActivity.class.getSimpleName());
        super.onDestroy();
    }

}
